﻿using System;
using System.Runtime.InteropServices;

namespace WiMo.Games.StandardCollision
{
    class HighResolutionStopWatch
    {
        private bool _isSupported = false;
        private double _frequency = 0;
        private Int64 _startTickCount = 0;
        private Int64 _endTickCount = 0;
        private bool _running = false;

        [DllImport("coredll.dll")]
        private static extern int QueryPerformanceCounter(ref Int64 count);

        [DllImport("coredll.dll")]
        private static extern int QueryPerformanceFrequency(ref Int64 count);

        public HighResolutionStopWatch()
        {
            Int64 rawFrequency = 0;

            int retValue = QueryPerformanceFrequency(ref rawFrequency);
            if (retValue != 0 && rawFrequency != 1000)
            {
                _isSupported = true;
                _frequency = Convert.ToDouble(rawFrequency);
            }
            else
            {
                _isSupported = false;
                _frequency = 1000.0;
            }
        }

        private Int64 Value
        {
            get
            {
                Int64 tickCount = 0;
                if (_isSupported)
                    QueryPerformanceCounter(ref tickCount);
                else
                    tickCount = (Int64)Environment.TickCount;

                return tickCount;
            }
        }

        public void Start()
        {
            _startTickCount = Value;
            _running = true;
        }

        public void Stop()
        {
            _endTickCount = Value;
            _running = false;
        }

        public double EllapsedMS
        {
            get
            {
                Int64 ellapsedTicks = (_running) ? Value - _startTickCount : _endTickCount - _startTickCount;

                return (ellapsedTicks * 1000.0) / _frequency;
            }
        }

        public override string ToString()
        {
            return string.Format("Ellapsed: {0:0.000}ms", EllapsedMS);
        }
    }
}
